package com.AnywheeBt;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.SeekBar;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.bluetooth.BluetoothAvrcp;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothA2dpSink;

import android.widget.TextView;
import java.text.SimpleDateFormat;


import java.io.IOException;
import java.io.UnsupportedEncodingException;


public class BtMusic extends Activity{
	private static final String TAG = "BtMusic";

	private static final byte AVRC_EVT_PLAY_STATUS_CHANGE = 0x01;
	private static final byte AVRC_EVT_TRACK_CHANGE	= 0x02;
	private static final byte AVRC_EVT_TRACK_REACHED_END = 0x03;
	private static final byte AVRC_EVT_TRACK_REACHED_START = 0x04;
	private static final byte AVRC_EVT_PLAY_POS_CHANGED	= 0x05;
	private static final byte AVRC_EVT_BATTERY_STATUS_CHANGE = 0x06;
	private static final byte AVRC_EVT_SYSTEM_STATUS_CHANGE = 0x07;
	private static final byte AVRC_EVT_APP_SETTING_CHANGE = 0x08;

	private static final byte AVRC_STOPPED = 0x00;
	private static final byte AVRC_PLAYING = 0x01;
	private static final byte AVRC_PAUSED =	0x02;
	

	
	private View BtMusicReturn;
	private View BtMusicMovePrevious;
	private View BtMusicPlay;
	private View BtMusicMovenext;
	private View BtMusicPause;
	private View BtMusicVolumeUp;
	private View BtMusicVolumeDown;
	private BroadcastMain receiver;
	private TextView songnameText;
	private TextView artistnameText;
	private TextView albumnameText;
	private TextView songlengthText;
	private TextView songposText;
	private byte ctPlayStatus = 0;
	private	int songlength = 0;
	private	int songPosition = 0;
	private SeekBar mSeekBar;
	private final static int UPDATE_POS_TIME = 0;
	private static final int AVRCP_CT_DATA_RESPONSE = 400;
	private Handler mHandler =null; 
	
	public static int playStat = BluetoothA2dpSink.STATE_NOT_PLAYING;
    @Override
	protected void onDestroy() {
        Log.i(TAG,"onDestroy");
    	super.onDestroy();
		mHandler =null;
		SzhBAction.setCtHandler(null);
		if(receiver != null)
			getApplicationContext().unregisterReceiver(receiver);
    }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bt_music);
		BtMusicReturn = (View) this.findViewById(R.id.bt_music_return);
		BtMusicMovePrevious = (View) this.findViewById(R.id.bto_music_moveprevious);
		BtMusicPlay = (View) this.findViewById(R.id.bto_music_play);
		BtMusicMovenext = (View) this.findViewById(R.id.bto_music_movenext);
		BtMusicPause = (View) this.findViewById(R.id.bto_music_pause);
		songnameText =(TextView)this.findViewById(R.id.bt_songname_text);
		artistnameText =(TextView)this.findViewById(R.id.bt_artistname_text);
		albumnameText = (TextView)this.findViewById(R.id.bt_albumname_text);
		songlengthText = (TextView)this.findViewById(R.id.bt_song_length);
		
		songposText = (TextView)this.findViewById(R.id.bt_song_pos);
		mSeekBar = (SeekBar) findViewById(R.id.progress);
		mSeekBar.setEnabled(false);

		songlengthText.setText("00:00:00");
		songposText.setText("00:00:00");

		mHandler = new Handler() {
				public void handleMessage(android.os.Message msg) {
					switch (msg.what) {
					case UPDATE_POS_TIME:
						updatePosTime();
						break;
					case AVRCP_CT_DATA_RESPONSE:
						byte[] data  = (byte[]) msg.obj;
						Log.e(TAG,"AVRCP_CT_DATA_RESPONSE len:"+msg.arg1+" pdu:"+data[0]);
						pareCtData(data);
						break;
					default:
						break;
					}
				}
			};

		receiver = new BroadcastMain();
		IntentFilter filter = new IntentFilter();
        filter.addAction("android.bluetooth.a2dp.sink.profile.action.PLAYING_STATE_CHANGED");
        getApplicationContext().registerReceiver(receiver, filter);
		SzhBAction.setCtHandler(mHandler);
		
		SzhBAction.SetBtPassThroughCmd(0x10,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
		SzhBAction.SetBtPassThroughCmd(0x11,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
		//SzhBAction.SetBtPassThroughCmd(0x14,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);

		if(playStat == BluetoothA2dpSink.STATE_PLAYING){
			BtMusicPlay.setVisibility(View.VISIBLE);
			BtMusicPause.setVisibility(View.GONE);
		}else if(playStat == BluetoothA2dpSink.STATE_NOT_PLAYING){
			BtMusicPlay.setVisibility(View.GONE);
			BtMusicPause.setVisibility(View.VISIBLE);
		}
//		BtMusicVolumeUp  = (View) this.findViewById(R.id.volume_up);
//		BtMusicVolumeDown = (View) this.findViewById(R.id.volume_down);
		if (BtMusicVolumeUp != null) {
			BtMusicVolumeUp.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, ">>>>>>>>>>>>>>>>BtMusicVolumeUp<<<<<<<<<<<<<");
				}
			});
		}
		
		if (BtMusicVolumeDown != null) {
			BtMusicVolumeDown.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, ">>>>>>>>>>>>>>>>BtMusicVolumeDown<<<<<<<<<<<<<");
				}
			});
		}

		if (BtMusicPlay != null) {//pause
			BtMusicPlay.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, "BtMusicPause playStat:"+playStat);
					if(playStat == BluetoothA2dpSink.STATE_NOT_PLAYING)
						return;
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_PAUSE,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_PAUSE,BluetoothAvrcp.PASSTHROUGH_STATE_RELEASE);

					BtMusicPlay.setVisibility(View.GONE);
					BtMusicPause.setVisibility(View.VISIBLE);
				}
			});
		}

		if (BtMusicPause != null) {//play
			BtMusicPause.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, "BtMusicPlay playStat:"+playStat);
					if(playStat == BluetoothA2dpSink.STATE_PLAYING)
						return;
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_PLAY,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_PLAY,BluetoothAvrcp.PASSTHROUGH_STATE_RELEASE);

					BtMusicPlay.setVisibility(View.VISIBLE);
					BtMusicPause.setVisibility(View.GONE);
				}
			});
		}

		if (BtMusicReturn != null) {
			BtMusicReturn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, ">>>>>>>>>>>>>>>>BtMusicReturn<<<<<<<<<<<<<");
					onBackPressed();
				}
			});
		}

		if (BtMusicMovePrevious != null) {
			BtMusicMovePrevious.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG,
							">>>>>>>>>>>>>>>>BtMusicMovePrevious<<<<<<<<<<<<<");
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_BACKWARD,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_BACKWARD,BluetoothAvrcp.PASSTHROUGH_STATE_RELEASE);
				}
			});
		}

		if (BtMusicMovenext != null) {
			BtMusicMovenext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e(TAG, ">>>>>>>>>>>>>>>>BtMusicMovenext<<<<<<<<<<<<<");
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_FORWARD,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
					SzhBAction.SetBtPassThroughCmd(BluetoothAvrcp.PASSTHROUGH_ID_FORWARD,BluetoothAvrcp.PASSTHROUGH_STATE_RELEASE);
				}
			});
		}
		
	}

	private  int byteArrayToInt32(byte[] b,int pos) {
		return   b[pos+3] & 0xFF |  
            (b[pos+2] & 0xFF) << 8 |  
            (b[pos+1] & 0xFF) << 16 |  
            (b[pos+0] & 0xFF) << 24; 
	}
	private  int byteArrayToInt16(byte[] b,int pos) {
		return   b[pos+1] & 0xFF |  
            (b[pos+0] & 0xFF) << 8;
	}
	void getElementAttr(byte[] data){
		int j =0;
		int i;
		int numAttr= data[4]&0xff;
		int attr_id;
		int charset_id;
		int txtLen;
		
		j += 5;
		for(i=0;i<numAttr;i++){
			attr_id = byteArrayToInt32(data,j);
			j += 4;
			charset_id = byteArrayToInt16(data,j);
			j += 2;
			txtLen = byteArrayToInt16(data,j);
			j += 2;
			byte[] attrtext= new byte[txtLen];
			System.arraycopy(data,j,attrtext,0,txtLen);
			String name=null;
			try {						
				name = new String(attrtext,"UTF-8");					
			} catch (UnsupportedEncodingException e) {						
				e.printStackTrace();
			}

			if(attr_id==1)
				songnameText.setText(name);
			else if(attr_id ==2)
				artistnameText.setText(name);
			else if(attr_id ==3)
				albumnameText.setText(name);
			j += txtLen;
		}
	}
	
	private void updatePosTime(){
		if( ctPlayStatus == AVRC_PLAYING &&mHandler!=null){
			mHandler.sendEmptyMessageDelayed(UPDATE_POS_TIME, 1000);
			Log.e(TAG, "updatePosTime ctPlayStatus:"+ctPlayStatus);
			SzhBAction.SetBtPassThroughCmd(0x11,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);//every second use getPlayStatus to get play time
			//songposText.setText((getTimeString(songPosition)));
			//mSeekBar.setProgress(songPosition);
			//songPosition ++;
		}		
	}
	private void updatePosTime(byte newPlaystat){
		//songposText.setText((getTimeString(songPosition)));
		//mSeekBar.setProgress(songPosition);
		if(newPlaystat == AVRC_PLAYING && ctPlayStatus != AVRC_PLAYING &&mHandler!=null){
			mHandler.sendEmptyMessageDelayed(UPDATE_POS_TIME, 1000);
			//songPosition ++;
		}
		
		ctPlayStatus = newPlaystat;	
	}

	private String getTimeString(int time){
		String timeStr = "";
        int h = time / 3600;
        int m = time % 3600 / 60;
        int s = time % 60;
        timeStr = "" + (h > 9 ? h : "0" + h) + ":" + (m > 9 ? m : "0" + m) + ":"
                + (s > 9 ? s : "0" + s);
		return timeStr;
	}

	void getPlayStatus(byte[] data){
		int j=0;
		j += 2;
		int len = byteArrayToInt16(data,j);
		if(len < 9)return;
		j += 2;
		int lengthMs = byteArrayToInt32(data,j);
		songlength = lengthMs/1000;
		//if((lengthMs%1000)>500)
		//	songlength ++;
		j += 4;
		int PositionMs = byteArrayToInt32(data,j);
		songPosition = PositionMs/1000;
		//if((PositionMs%1000)>500)
		//	songPosition ++;
		j += 4;
		
		updatePosTime(data[j]);


		//SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		//String hms = formatter.format(songlength);
		songlengthText.setText(getTimeString(songlength));
		mSeekBar.setMax(songlength);
		//hms = formatter.format(songPosition);
		
		songposText.setText((getTimeString(songPosition)));
		mSeekBar.setProgress(songPosition);
	}

	void registerNotifyRsp(byte[] data){
		int j=0;
		j += 2;
		int len = byteArrayToInt16(data,j);
		j += 2;
		byte eventID = data[j];
		j ++;
		if(eventID == AVRC_EVT_PLAY_STATUS_CHANGE){
			SzhBAction.SetBtPassThroughCmd(0x11,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
		}else if(eventID == AVRC_EVT_TRACK_CHANGE){
			SzhBAction.SetBtPassThroughCmd(0x10,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
			SzhBAction.SetBtPassThroughCmd(0x11,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
		}else if(eventID == AVRC_EVT_PLAY_POS_CHANGED){//no use this.use getPlayStatus to get play time
			SzhBAction.SetBtPassThroughCmd(0x14,BluetoothAvrcp.PASSTHROUGH_STATE_PRESS);
			songPosition = byteArrayToInt32(data,j)/1000;
			songposText.setText((getTimeString(songPosition)));
			mSeekBar.setProgress(songPosition);
		}
	}
	private void pareCtData(byte[] data){
		byte pdu = data[0];
		if(pdu == 0x20){//AVRC_PDU_GET_ELEMENT_ATTR               0x20
			getElementAttr(data);
		}else if(pdu == 0x30){
			getPlayStatus(data);
		}else if(pdu == 0x31){
			registerNotifyRsp(data);
		}
	}
	public 	class BroadcastMain extends BroadcastReceiver {    
	    @Override  
	    public void onReceive(Context context, Intent intent) { 
    		String action = intent.getAction();
			Log.e(TAG, "BroadcastMain rec:"+action);
			if(action.equals("android.bluetooth.a2dp.sink.profile.action.PLAYING_STATE_CHANGED")){
				playStat = (int)intent.getExtras().get(BluetoothProfile.EXTRA_STATE);
				Log.e(TAG, "BroadcastMain playStat:"+playStat);
				if(playStat == BluetoothA2dpSink.STATE_PLAYING){
					BtMusicPlay.setVisibility(View.VISIBLE);
					BtMusicPause.setVisibility(View.GONE);
				}else if(playStat == BluetoothA2dpSink.STATE_NOT_PLAYING){
					BtMusicPlay.setVisibility(View.GONE);
					BtMusicPause.setVisibility(View.VISIBLE);
				}
			}
	    } 
	}  
}
